package com.dingreading.cloud.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.config.ResourceHandlerRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

@Primary
@Component
public class SwaggerProvider implements SwaggerResourcesProvider, WebFluxConfigurer {
    /**
     * Swagger2默认的url后缀
     */
    public static final String SWAGGER2URL = "/v2/api-docs";
    /**
     * 网关路由
     */
    @Lazy
    @Autowired
    private RouteLocator routeLocator;
    @Autowired
    private GatewayProperties gatewayProperties;

    /**
     * 聚合其他服务接口(swagger右上角下拉框，可聚合其它服务)
     * springfox-swagger 提供的分组接口是 swagger-resource，
     * 返回的是分组接口名称、地址等信息，而在Spring Cloud微服务架构下，
     * 我们需要重写该接口，改由通过网关的注册中心动态发现所有的微服务文档
     *
     * @return
     */
    @Override
    public List<SwaggerResource> get() {
        //接口资源列表
        List<SwaggerResource> resourceList = new ArrayList<>();
        //服务名称列表
        List<String> routes = new ArrayList<>();
        // 获取网关中配置的route
        // 1. 获取路由 - id => 为服务名 => order-route
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
        //结合配置的route-路径（Path）和route过滤，只获取有效的route节点
        gatewayProperties.getRoutes().stream()
                .filter(routeDefinition -> routes
                        .contains(routeDefinition.getId()))
                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
                        .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
                        //去掉auth-service服务
                        .filter(predicateDefinition -> !"auth-service".equalsIgnoreCase(routeDefinition.getId()))
                        .forEach(predicateDefinition -> resourceList
                                .add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()
                                        //处理为默认的url后缀， /system/v2/api-docs
                                        .get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER2URL)))));
        return resourceList;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name); // 设置名称
        swaggerResource.setLocation(location);// 设置访问地址
        swaggerResource.setSwaggerVersion("3.0.0");
        return swaggerResource;
    }

    //    swagger 资源映射路径，3.0.0版本访问是： /swagger-ui/index.html
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** swagger-ui 地址 */
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }
}
